/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2023. All rights reserved.
 */

package util

import (
	"io"
	"io/ioutil"
	"net/http"
)

type HClient struct {
	hClient *http.Client
}
type TLSConf struct {
	Cert string
	Key  string
	Root string
}

type Identity struct {
	Name string
	Type string
	Cert string
	Key  string
}
type Service struct {
	Url       string
	Type      string
	ProjectId string
}

func NewHttpsClient() *HClient {
	httpClient := &HClient{
		hClient: &http.Client{},
	}
	return httpClient
}

// 创建通用的请求头
func BuildHeader() map[string]string {
	hearders := make(map[string]string)
	hearders["Accept"] = "application/json"
	hearders["Content-Type"] = "application/json;charset=utf-8"
	return hearders
}

// 创建http请求
func BuildHttpRequest(requestMothed, resourcePath string, headers map[string]string, body io.Reader) (*http.Request, error) {
	req, err := http.NewRequest(requestMothed, resourcePath, body)
	if err != nil {
		return nil, err
	}
	req.Close = true
	for k, v := range headers {
		req.Header.Set(k, v)
	}
	return req, nil
}

// 发送http请求
func (client *HClient) Request(requestMothed, resourcePath string, headers map[string]string, body io.Reader) (int, []byte, map[string][]string, error) {
	if headers == nil {
		headers = BuildHeader()
	}
	req, err := BuildHttpRequest(requestMothed, resourcePath, headers, body)
	if err != nil {
		return 0, nil, nil, err
	}
	response, err := client.hClient.Do(req)
	if err != nil {
		return 0, nil, nil, err
	}
	defer response.Body.Close()
	var buffer []byte
	buffer, err = ioutil.ReadAll(response.Body)
	if err != nil {
		return 0, nil, nil, err
	}
	return response.StatusCode, buffer, response.Header, nil
}
